package com.example.orderfood2;

import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.RecyclerViewAdapter.TeacherAdapter;
import com.example.orderfood2.RecyclerViewAdapter.TeacherOperateStudentAdapter;
import com.example.orderfood2.Repository.ManagerRepository;
import com.example.orderfood2.Repository.StudentRepository;
import com.example.orderfood2.Repository.TeacherRepository;
import com.example.orderfood2.entity.Student;
import com.example.orderfood2.entity.Teacher;
import com.example.orderfood2.managerOperate.AddStudentActivity;
import com.example.orderfood2.util.DBUtil;
import com.example.orderfood2.viewAllInformation.EditStudentActivity;
import com.example.orderfood2.viewAllInformation.EditTeacherActivity;

import java.util.List;

public class TeacherActivity extends AppCompatActivity implements TeacherOperateStudentAdapter.OnItemClickListener{
//    DBUtil dbUtil;
    private TeacherRepository dbUtil;
    private StudentRepository dbUtil1;
    private int Id;
    private RecyclerView recyclerView;
    private TeacherOperateStudentAdapter adapter;
    private Teacher teacher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_teacher);

        dbUtil= DatabaseManager.getInstance(this).getTeacherRepository();
        dbUtil1= DatabaseManager.getInstance(this).getStudentRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);

//        setContentView(R.layout.activity_teacher);
        //创建数据库
//        dbUtil=new DBUtil(this);

        /// 获取传递过来的 Intent 对象
        android.content.Intent intent = getIntent();
        // 获取传递的 account 数据
        String account=intent.getStringExtra("account");
        //获得登录老师的全部信息
        teacher=dbUtil.getTeacherByUsername(account);
        //获得Id值
        Id=teacher.getId();
        // 导入正确的 Toolbar 类并设置为 ActionBar
        Toolbar toolbar=findViewById(R.id.teacher_toolbar);
        setSupportActionBar(toolbar);
        //设置账号名字
        TextView teacher_name=findViewById(R.id.teacher_name);
        teacher_name.setText(account);
// 动态设置 Toolbar 标题
// 修改 Toolbar 的标题
        if (teacher != null) {
            if (teacher.getScience() != null) {
                String title = "学科：" + teacher.getScience() + "的学生列表";
                getSupportActionBar().setTitle(title);
            } else {
                getSupportActionBar().setTitle("学科：未知学科的学生列表");
            }
        } else {
            getSupportActionBar().setTitle("学科：未知学科的学生列表");
        }
        //      退出代码
        Button manage_to_login=findViewById(R.id.teacher_to_login);
        manage_to_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent(TeacherActivity.this, MainActivity.class);
                // 设置标志以清除任务栈（关键修改）
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                // 结束当前Activity（确保退出）
                finish();
            }
        });
        //给左上图标添加点击事件，并完成左侧边栏弹出
        LinearLayout leftSiderbar=findViewById(R.id.Left_sidebar_teacher);
        View overlay=findViewById(R.id.overlay);
        //        用数组传值
        final int[] targetWidth = {0};
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取参数对象
                FrameLayout.LayoutParams params=(FrameLayout.LayoutParams) leftSiderbar.getLayoutParams();
                // 检查当前宽度，如果是0dp就改为300dp，否则改回0dp（实现点击切换）
                if(params.width==0){
                    // 将300dp转换为像素
                    targetWidth[0] = (int) (300 * getResources().getDisplayMetrics().density);
                    // 创建一个ValueAnimator
                    ValueAnimator animator = ValueAnimator.ofInt(0, targetWidth[0]);
                    animator.setDuration(300);
                    animator.setInterpolator(new LinearInterpolator());
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
                            // 获取当前动画的值
                            int value = (int) valueAnimator.getAnimatedValue();
                            // 更新布局参数的宽度
                            params.width = value;
                            leftSiderbar.setLayoutParams(params);
                        }
                    });
                    animator.start(); // 启动动画
                    overlay.setVisibility(View.VISIBLE);//将隐藏改为可以操作
                }
            }
        });
        //添加点击事件，当用户触摸大于300的位置时，leftSidebar 由300到0
        overlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取参数对象
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) leftSiderbar.getLayoutParams();
                if (params.width > 0){
                    // 创建一个ValueAnimator，从当前宽度过渡到0
                    ValueAnimator animator = ValueAnimator.ofInt(params.width, 0);
                    animator.setDuration(300); // 动画持续时间，单位为毫秒
                    animator.setInterpolator(new LinearInterpolator()); // 设置插值器，使动画匀速进行
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            // 获取当前动画的值
                            int value = (int) animation.getAnimatedValue();
                            // 更新布局参数的宽度
                            params.width = value;
                            leftSiderbar.setLayoutParams(params);
                        }
                    });
                    animator.start(); // 启动动画
                    overlay.setVisibility(View.GONE);//将可以操作改为隐藏
                }
            }
        });
//        密码修改
        Button teacher_change_password=findViewById(R.id.teacher_change_password);
        teacher_change_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //添加Dialog组件
                PasswordChangeDialogTeacher.showPasswordChangeDialogTeacher(TeacherActivity.this,account);
            }
        });
        //        用户注销
        Button delete_teacher=findViewById(R.id.delete_teacher);
        delete_teacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbUtil.deleteTeacher(teacher.getId());
                Toast.makeText(TeacherActivity.this,"用户"+account+"成功注销",Toast.LENGTH_SHORT).show();
                Intent intent1=new Intent(TeacherActivity.this,MainActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent1);
                finish();
            }
        });
        //展示个人信息
        Button see_information=findViewById(R.id.see_information);
        see_information.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //复用EditTeacherActivity
                Intent intent = new Intent(TeacherActivity.this, EditTeacherActivity.class); // 跳转到编辑页面
                intent.putExtra("source", "TeacherActivity"); // 添加来源标识
                intent.putExtra("id", Id);
                startActivity(intent);
            }
        });
        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recyclerClassesView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //        获取搜索框和按钮
        TextView search_text=findViewById(R.id.search_student_name);
        Button search_button=findViewById(R.id.search_student_button);
//        给按钮绑定监听事件，搜索学生
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name=search_text.getText().toString();
                List<Student> students=dbUtil1.getStudentsByName(name);
//                展示数据
                adapter = new TeacherOperateStudentAdapter(students, TeacherActivity.this);
                adapter.setOnItemClickListener(TeacherActivity.this);
                recyclerView.setAdapter(adapter);

            }
        });
        // 加载学生数据
        loadStudents();
    }
    // 在 TeacherActivity 类中添加 onResume 方法
    //每当从添加页面回来后刷新页面
    @Override
    protected void onResume() {
        super.onResume();
        loadStudents(); // 每次返回到该页面时刷新列表
    }
    //    将R.menu.teacher_menu中的布局给toolbar
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.teacher_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }
    private void loadStudents() {
        // 获取当前老师的学科
        String account = getIntent().getStringExtra("account");
        Teacher teacher = dbUtil.getTeacherByUsername(account);

        if (teacher != null && teacher.getScience() != null) {
            // 从数据库获取该学科下的学生列表
            List<Student> students = dbUtil.getStudentsByTeacherScience(teacher.getScience());
            // 初始化适配器
            adapter = new TeacherOperateStudentAdapter(students,this);
            adapter.setOnItemClickListener(TeacherActivity.this);// 设置按钮点击监听器
            recyclerView.setAdapter(adapter);
        } else {
            Toast.makeText(this, "无法获取学生列表", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onEditClick(int position, int id, String username) {
        Intent intent = new Intent(this, EditStudentActivity.class); // 跳转到编辑页面
        intent.putExtra("id", id);
        intent.putExtra("source", "TeacherActivity"); // 添加来源标识
        startActivity(intent);
    }

    @Override
    public void onDeleteClick(int position, int id) {
    new AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定删除此同学吗?")
            .setPositiveButton("确定",(dialog,which)->{
                dbUtil1.deleteStudent(id); // 从数据库删除
                loadStudents(); // 刷新列表
            })
            .setNegativeButton("取消",null)
            .show();

    }

    @Override
    public void onAddCourseClick(int position, int id) {
        Intent intent = new Intent(this, AddCourse.class);
        intent.putExtra("id", String.valueOf(id));
        startActivity(intent);
    }

    //给右上角的选项添加事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id=item.getItemId();
        if(id==R.id.teacher_add_student){
            Intent AddStudentActivity=new Intent(TeacherActivity.this,AddStudentActivity.class);
            AddStudentActivity.putExtra("science",teacher.getScience());
            startActivity(AddStudentActivity);
        } else if (id==R.id.add_school_new) {
            Intent AddStudentActivity=new Intent(TeacherActivity.this, AddSchoolNew.class);
            startActivity(AddStudentActivity);
        } else {
            Intent AddStudentActivity=new Intent(TeacherActivity.this,class_rank.class);
            AddStudentActivity.putExtra("science",teacher.getScience());
            startActivity(AddStudentActivity);
        }
        return super.onOptionsItemSelected(item);
    }
}